#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
任务1主运行脚本
整合所有功能：特征提取、消融实验、PCA分析、SHAP分析
"""

import os
import sys
import warnings
warnings.filterwarnings('ignore')

def main():
    """主函数"""
    print("=== 任务1：数据分析与故障特征提取 ===")
    print("开始运行完整的特征提取和分析流程...\n")
    
    # 检查code目录是否存在
    code_dir = os.path.join(os.path.dirname(__file__), 'code')
    if not os.path.exists(code_dir):
        print(f"错误: code目录不存在: {code_dir}")
        return
    
    # 检查源域数据集是否存在
    data_dir = "D:\..MBA\数学建模\model\源域数据集"
    if not os.path.exists(data_dir):
        print(f"错误: 源域数据集目录不存在: {data_dir}")
        print("请确保源域数据集文件夹在正确位置")
        return
    
    # 切换到code目录
    original_dir = os.getcwd()
    os.chdir(code_dir)
    
    try:
        # 添加code目录到Python路径
        sys.path.insert(0, code_dir)
        
        # 1. 特征提取
        print("步骤1: 特征提取")
        print("-" * 50)
        from feature_extraction import main as extract_features
        analyzer, features_df = extract_features()
        
        if features_df is None:
            print("特征提取失败，请检查数据路径")
            return
        
        print("特征提取完成！\n")
        
        # 2. 消融实验
        print("步骤2: 消融实验")
        print("-" * 50)
        from ablation_study import main as run_ablation
        run_ablation()
        print("消融实验完成！\n")
        
        # 3. PCA分析
        print("步骤3: PCA分析")
        print("-" * 50)
        from pca_feature_reduction import reduce_features_with_pca
        df_reduced, reducer, pca_results = reduce_features_with_pca()
        print("PCA分析完成！\n")
        
        # 4. SHAP分析
        print("步骤4: SHAP分析")
        print("-" * 50)
        from tree_model_shap_analysis import main as run_shap
        run_shap()
        print("SHAP分析完成！\n")
        
        # 5. 特征选择指南
        print("步骤5: 特征选择指南")
        print("-" * 50)
        from feature_selection_guide import main as run_guide
        run_guide()
        print("特征选择指南完成！\n")
        
        print("=== 任务1完成 ===")
        print("所有分析结果已保存到 results/ 文件夹")
        print("生成的主要文件:")
        print("- bearing_features.csv: 提取的特征数据")
        print("- ablation_results.csv: 消融实验结果")
        print("- reduced_features.csv: PCA降维结果")
        print("- 各种可视化图表和分析报告")
        
    except Exception as e:
        print(f"运行过程中出现错误: {e}")
        import traceback
        traceback.print_exc()
        return
    finally:
        # 恢复原始工作目录
        os.chdir(original_dir)

if __name__ == "__main__":
    main()
